﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Upreader.Usenet.Nntp
{
    public class ResponseMessage
    {
        #region Configuration

        private const char Space = ' ';
        
        #endregion // Configuration

        #region Fields

        private string _line;

        #endregion // Fields

        #region Constructor 

        public ResponseMessage(string line)
        {
            if (line == null)
                throw new ArgumentNullException("line");
            if (line.Length < 3)
                throw new ArgumentException(Resource.ResponseMessage_LineToShort, "line");

            _line = line;
        }

        #endregion // Constructor

        #region Methods

        public int ParseResponseCode()
        {
            return Convert.ToInt32(_line.Substring(0, 3), System.Globalization.CultureInfo.InvariantCulture);
        }

        public string ParseText()
        {
            // if there is no text, only a code
            if (_line.Length < 4)
                return string.Empty;

            return _line.Substring(4);
        }

        public IEnumerable<string> ParseArguments()
        {
            return ParseArguments(-1);
        }

        public IEnumerable<string> ParseArguments(int expectedArgumentCount)
        {
            string[] arguments = _line.Split(Space);
            
            // We start with one since the first parsed argument is not the argument but response code
            if (expectedArgumentCount == -1)
                expectedArgumentCount = arguments.Length - 1; 

            for (int current = 1; current <= expectedArgumentCount; current++)
            {
                yield return arguments[current];
            }
        }

        public override string ToString()
        {
            return _line;
        }

        #endregion // Methods
    }
}
